package com.example.spark.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.spark.entity.User;
import com.example.spark.entity.dto.PaginationDTO;
import com.example.spark.entity.result.CommonResult;
import com.example.spark.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@CrossOrigin
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 查询所有用户加模糊查询加分页
     *
     * @param userDto dto
     * @return CommonResult
     * @throws JsonProcessingException
     */
    @GetMapping("/getUsers")
    public CommonResult<IPage<User>> getAll(@RequestParam(value = "data") String userDto) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        TypeFactory typeFactory = objectMapper.getTypeFactory();
        JavaType javaType = typeFactory.constructParametricType(PaginationDTO.class, User.class);
        PaginationDTO<User> dto = objectMapper.readValue(userDto, javaType);
        Integer currentPage = dto.getCurrentPage();
        Integer pageSize = dto.getPageSize();
        User user = dto.getEntity();
        IPage<User> page = userService.getAllByPage(currentPage, pageSize, user);
        //访问页判断
        if (currentPage > page.getPages()) {
            page = userService.getAllByPage((int) page.getPages(), pageSize, user);
        }
        return new CommonResult<>(200, "success", page);
    }

    /**
     * 通过id删除用户
     *
     * @param id 用户id
     * @return CommonResult
     */
    @DeleteMapping("/deleteUserById/{id}")
    public CommonResult deleteById(@PathVariable Long id) {
        return userService.deleteById(id);
    }

    /**
     * 添加用户
     *
     * @param user 用户
     * @return CommonResult
     */
    @PostMapping("/addUser")
    public CommonResult add(@RequestBody User user) {
        return userService.add(user);
    }

    /**
     * 添加/修改用户图片
     *
     * @param file 图片文件
     * @param id   用户id
     * @return CommonResult
     * @throws IOException
     */
    @PutMapping("/updatePicture/{id}")
    public CommonResult addPicture(@RequestParam MultipartFile file, @PathVariable Long id) throws IOException {
        return userService.addPicture(file, id);
    }

    /**
     * 修改用户信息
     *
     * @param user 用户
     * @return CommonResult
     */
    @PutMapping("/updateUser")
    public CommonResult update(@RequestBody User user) {
        return userService.update(user);
    }
}
